import React, { useEffect, useState } from 'react'
import { debounce } from 'lodash'
import * as echarts from 'echarts'

export type EChartsOption = echarts.EChartsOption

const useEcharts = (
  // dom实例
  ref: React.RefObject<HTMLDivElement | HTMLCanvasElement | undefined>,
  // echarts配置
  initOption: EChartsOption,
  // 回调函数
  cb?: (ec: echarts.ECharts) => any,
  // 依赖的数据
  list?: any[],
  // 是否开启监听依赖数据变化
  isOpen = false,
  // 主题
  theme = '',
): {
  echart: echarts.ECharts | undefined
  cb: (ec: echarts.ECharts) => void
} => {
  const [chart, setChart] = useState<echarts.ECharts>()

  // 判断传入得是不是回调函数
  const callback = (ec: echarts.ECharts) => {
    if (typeof cb === 'function') {
      cb(ec)
    }
  }

  useEffect(() => {
    if (ref.current) {
      // 初始化
      const c = echarts.init(ref.current, theme)
      // 存储实例
      setChart(c)
      c.setOption(initOption)
      callback(c)
    }
  }, [ref])

  useEffect(() => {
    // 在这里监听，放在里面会内存泄漏，一个优化吧
    let resizeHandler: any
    if (chart) {
      resizeHandler = debounce(() => {
        chart?.resize()
      }, 100)
      window.addEventListener('resize', resizeHandler)
    }

    return () => {
      if (chart) {
        chart?.dispose()
        window.removeEventListener('resize', resizeHandler)
      }
    }
  }, [chart])

  useEffect(() => {
    // 场景为数据发生变化时可以传入list和isOpen开启重新渲染
    if (isOpen && list && chart) {
      callback(chart)
    }
  }, [list, chart, isOpen])

  return {
    echart: chart,
    cb: callback,
  }
}

export default useEcharts
